<template>
  <div class="login-wrapper">
    <div class="modal">
      <el-form ref="userForm" :model="user" status-icon :rules="rules">
        <div class="title">火星</div>
        <el-form-item prop="userName">
          <!-- <Edit /> -->
          <el-input type="text" prefix-icon="User" v-model="user.userName" />
        </el-form-item>
        <el-form-item prop="userPwd">
          <el-input type="password" prefix-icon="View" v-model="user.userPwd" />
        </el-form-item>
        <el-form-item>
          <el-button class="btn-login" type="primary" @click="login"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import storage from "../utils/storage";
import utils from "../utils/utils";
const { proxy } = getCurrentInstance();

const user = ref({
  userName: "admin",
  userPwd: "123456",
});

const rules = ref({
  userName: [
    {
      required: true,
      message: "请输入用户名",
      trigger: "blur",
    },
  ],
  userPwd: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
  ],
});

const router = useRouter();
const goHome = () => {
  router.push("/");
};

const store = useStore();

const userForm = ref(null);
const login = () => {
  // console.log(userForm.value.validate);
  userForm.value.validate((valid) => {
    // console.log(valid);
    if (valid) {
      proxy.$api.login(user.value).then(async (res) => {
        store.commit("saveUserInfo", res);
        await loadAsyncRoutes();
        router.push("/welcome");
      });
    } else {
      return false;
    }
  });

  const loadAsyncRoutes = async () => {
    let userInfo = storage.getItem("userInfo") || {};
    if (userInfo.token) {
      try {
        const { menuList } = await proxy.$api.getPermissionList();
        let routes = utils.generateRoute(menuList);
        routes.map((route) => {
          let url = `./../views/${route.component}.vue`;
          route.component = () => import(url);
          router.addRoute("home", route);
        });
      } catch (error) {
        console.log('error', error);
      }
    }
  };
};
</script>

<style lang="scss">
.login-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f9fcff;
  width: 100vw;
  height: 100vh;

  .modal {
    width: 500px;
    padding: 50px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0px 0px 10px 3px #c7c9cb4d;
    .title {
      font-size: 50px;
      line-height: 1.5;
      text-align: center;
      margin-bottom: 30px;
    }

    .btn-login {
      width: 100%;
    }
  }
}
</style>
